package de.godlike.services.internal;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import de.godlike.services.internal.dataTypes.DiskInfo;

/**
 * @deprecated currently experimental!
 * 
 *             This class offers some information and methods to access the
 *             system. It only works for Linux-OS.
 * 
 * @author asmodaeus
 * 
 */
@Deprecated
public class SysAccessLinux {

	private final Logger logger = Logger.getLogger(SysAccessLinux.class);

	/**
	 * shutdown the system!
	 * 
	 * @param seconds2Live
	 *            seconds, until the system goes down (0 = now!)
	 */
	public void shutdown(int seconds2Live) {
		try {
			if (seconds2Live == 0) {
				new ProcessBuilder("sudo", "shutdown", "-h", "now").start();
			} else {
				double mins2Live = Math.ceil(seconds2Live / 60.0);
				new ProcessBuilder("sudo", "shutdown", "-h", "+"
						+ String.valueOf(new Double(mins2Live).intValue()))
						.start();
			}
		} catch (IOException e) {
			this.logger.error("shutdown error: " + e.getMessage(), e);
		}
	}

	/**
	 * restart the system
	 */
	public void restart() {
		try {
			new ProcessBuilder("sudo", "reboot").start();
		} catch (IOException e) {
			this.logger.error("restart error: " + e.getMessage(), e);
		}
	}

	/**
	 * @return the list of all mountpoints known in the OS with infos like
	 *         total/used/free Space.
	 */
	public List<DiskInfo> getDiskList() {
		List<DiskInfo> returnList = new ArrayList<DiskInfo>();

		try {
			Process pdf = Runtime.getRuntime().exec("df");
			BufferedReader in = new BufferedReader(new InputStreamReader(
					pdf.getInputStream()));

			String row = null;
			// Zeilenueberschrift
			in.readLine();
			while ((row = in.readLine()) != null) {
				row = row.replaceAll(" +", " ");
				if (row.split(" ")[0].equalsIgnoreCase("none")) {
					continue;
				}

				DiskInfo tmpDisk = new DiskInfo();
				tmpDisk.setMountPoint(row.split(" ")[5]);
				tmpDisk.setUsedSpace(row.split(" ")[2]);
				tmpDisk.setFreeSpace(row.split(" ")[3]);
				tmpDisk.setTotalSpace(row.split(" ")[1]);

				returnList.add(tmpDisk);
				tmpDisk = null;
			}
		} catch (IOException e) {
			this.logger.error("getDiskList error: " + e.getMessage(), e);
		}

		return returnList;
	}

	/**
	 * @deprecated Just 4 test!
	 * @param args
	 */
	@Deprecated
	public static void main(String[] args) {
		new SysAccessLinux().shutdown(30);
	}
}
